package com.niit.onlinemusicserver.controller;

import com.niit.onlinemusicserver.common.JwtUtils;
import com.niit.onlinemusicserver.common.R;
import com.niit.onlinemusicserver.common.RandomCodeGenerate;
import com.niit.onlinemusicserver.constant.Constants;
import com.niit.onlinemusicserver.model.domain.Consumer;
import com.niit.onlinemusicserver.model.request.ConsumerPhoneCodeRequest;
import com.niit.onlinemusicserver.service.ConsumerService;
import com.niit.onlinemusicserver.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import com.niit.onlinemusicserver.common.Token;
/**
 * 短信验证登录、微信扫码、支付宝扫码、人脸识别接口api
 */
@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ConsumerLoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private ConsumerService consumerService;

    /**
     * 发送验证码
     *
     * @param phone
     */
    @PostMapping("/sms")
    public R sendSmsCode(@RequestParam String phone) {
        return loginService.sendRCode(phone);
    }

    /**
     * 校验验证码
     *
     * @param codeRequest
     * @return
     */
    @PostMapping("/sms/code")
    public R checkSmsCode(@RequestBody ConsumerPhoneCodeRequest codeRequest) {
        return loginService.checkRCode(codeRequest);
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/mail/code")
    public R mailLoginCheck(@RequestParam String email) throws NoSuchAlgorithmException {
        //todo 先校验是否已注册,如果没有注册则启动自动注册流程
        //校验是否为注册用户
        String activationCode = String.valueOf(RandomCodeGenerate.createCode(6));
        String message = "邮箱验证码已发送!";
        if (!consumerService.existUserByEmail(email)) {
            Consumer consumer = new Consumer();
            consumer.setUsername(email);
            consumer.setEmail(email);
            consumer.setAvator("https://java-pp.oss-cn-hangzhou.aliyuncs.com/img/avatorImages/user.jpg");
            consumer.setPassword("123456");
            //MD5加密
            String password = DigestUtils.md5DigestAsHex((Constants.SALT + "123456").getBytes(StandardCharsets.UTF_8));
            consumer.setPassword(password);
            //如果不存在，创建用户对象并保存到数据库
            if (consumerService.insert(consumer)) {
                message = "已使用该邮箱自动注册,请查阅邮件后使用验证码登录!";
            } else {
                message = "注册失败,请手动注册!";
            }
        }
        return loginService.sendMailCode(email, activationCode, message);
    }

    /**
     * 验证登录邮箱验证码
     */
    @GetMapping("/mail/activate/{email}/{checkCode}")
    public R checkMailActive(@PathVariable("email") String mail, @PathVariable("checkCode") String code, HttpServletRequest request) {
        if (loginService.checkMailCode(mail, code)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", mail);
            R result = R.success("登录成功");
            String tokenStr = JwtUtils.generateToken(mail);
            Token token = new Token();
            token.setAuthorization(tokenStr);
            Consumer oneByUserName = consumerService.getOneByUserName(mail);
            token.setObj(oneByUserName);
            result.setData(token);
            return result;
        }
        return R.error("邮箱名或者验证码错误!");
    }
}
